package com.ttmusic.fragments.maintab;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ttmusic.activitys.MainActivity;
import com.ttmusic.activitys.R;
import com.ttmusic.core.MusicManager;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.utils.Logs;
import com.ttmusic.utils.Utils;
import com.ttmusic.utils.baidu.Artist;
import com.ttmusic.utils.baidu.BaiduMusicUtil;
import com.ttmusic.utils.baidu.Song;
import com.ttmusic.utils.baidu.SongInfoDownload;
import com.ttmusic.utils.baidu.SongSug;
import com.ttmusic.view.adapters.SearchSongAdapter;
import com.ttmusic.view.pullrefresh.SwipeLayout;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 在线搜索
 * @author Administrator
 *
 */
public class SearchOnlineFragment extends Fragment implements OnClickListener {
	
	private View view;
	private LayoutInflater inflater;
	private ImageView icon_back_tomain, btn_beginSearch;
	private EditText input_keyword;//搜索关键字
	private int pageNo = 1;
	private int pageSize = 20;
	//搜索关键字是否为歌手名
	private boolean isArtist = true;
	//搜索关键字上歌手名时搜索到的歌手信息对象
	private Artist art;
	private SwipeLayout pullRefreshLayout;
	//搜索结果
	private ListView listview_search_songs;
	private SearchSongAdapter searchSongAdapter;
	private TextView tv_listview_itemcount;//展示搜索到多少条数据
	/**
	 * 通过歌手id分页查询歌手的歌曲列表 当输入关键字搜索未包含artist时
	 */
	private Handler searchArtistSongListHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			JSONObject obj = JSONObject.parseObject(msg.obj.toString());
			JSONArray songlist = obj.getJSONArray("songlist");
			if(songlist.size() > 0) {
				//List<Song> songs = new ArrayList<Song>();
				Song song = null;
				for(int i=0;i<songlist.size();i++) {
					song = JSON.parseObject(songlist.get(i).toString(), Song.class);
					//songs.add(song);
					BaiduMusicUtil.queryDownloadUrlBySongId(song.getSong_id(), queryDownloadUrlHandler);
				}
				tv_listview_itemcount.setText("共搜索到" + obj.getIntValue("songnums") + "条相关信息");
			}else {
				//一条数据都没搜索到
				tv_listview_itemcount.setText("未搜索到任何相关信息");
			}
			if(obj.getInteger("havemore") == 1) {
				pullRefreshLayout.finishLoading(true);
				//还有更多数据
			}else{
				//没有更多数据了
				pullRefreshLayout.finishLoading(false);
			}
		}
	};
	
	/**
	 * 获取搜索结果--歌曲信息 当输入关键字搜索未包含artist时
	 */
	private Handler searchSongInfoHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == 200) {
				JSONObject obj = JSONObject.parseObject(msg.obj.toString());
				JSONObject bitrate = obj.getJSONObject("bitrate");
				JSONObject songinfo = obj.getJSONObject("songinfo");
				songinfo.put("file_duration", bitrate.getIntValue("file_duration"));
				Song song = JSON.parseObject(songinfo.toJSONString(), Song.class);
				BaiduMusicUtil.queryDownloadUrlBySongId(song.getSong_id(), queryDownloadUrlHandler);
			}
		}
	};
	
	/**
	 * 通过songid查询歌曲的文件地址
	 */
	private Handler queryDownloadUrlHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			JSONObject obj = JSONObject.parseObject(msg.obj.toString());
			if(obj.getInteger("errorCode") == 22000) {
				JSONArray array = obj.getJSONObject("data").getJSONArray("songList");
				JSONObject art = JSONObject.parseObject(array.get(0).toString());
				if(art.getString("artistId").contains(",")) {
					art.put("artistId", art.getString("artistId").split(",")[0]);
				}
//				System.out.println("正在转化：" + array.get(0).toString());
				SongInfoDownload songInfoDownload = JSON.parseObject(art.toString(), SongInfoDownload.class);

				//展示到ListView中
				searchSongAdapter.getSearchSongs().add(songInfoDownload);
				searchSongAdapter.notifyDataSetChanged();
				MainActivity.adapterCurrentShow = searchSongAdapter;
			}else{
				//一条数据都没搜索到
				tv_listview_itemcount.setText("在线播放网络音乐失败！");
			}
		}
	};
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.inflater = inflater;
		view = inflater.inflate(R.layout.fragment_search_online, null);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		btn_beginSearch = (ImageView)view.findViewById(R.id.btn_beginSearch);
		btn_beginSearch.setOnClickListener(this);
		icon_back_tomain = (ImageView)view.findViewById(R.id.icon_back_tomain);
		icon_back_tomain.setOnClickListener(this);
		input_keyword = (EditText)view.findViewById(R.id.input_keyword);
		pullRefreshLayout = (SwipeLayout)view.findViewById(R.id.pullRefreshLayout);
		listview_search_songs = (ListView)view.findViewById(R.id.listview_search_songs);
		searchSongAdapter = new SearchSongAdapter(getContext());
		//headerView
		View header = inflater.inflate(R.layout.listheader_footer_item_count, null);
        tv_listview_itemcount = (TextView) header.findViewById(R.id.tv_listview_itemcount);
        listview_search_songs.addHeaderView(header);
        listview_search_songs.setAdapter(searchSongAdapter);
		listview_search_songs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long index) {
				if(index >= 0 && index < searchSongAdapter.getSearchSongs().size()) {
					//Toast.makeText(getContext(), "item被点击了", Toast.LENGTH_SHORT).show();
					//点击后在线播放
					MainActivity.adapterCurrentPlay = searchSongAdapter;
					MusicManager.setPlayingList(searchSongAdapter.getSearchSongs());
					MainActivity.mManager.prepareAndPlay((int)index);
				}
			}
		});
		//自动弹出软键盘
		input_keyword.requestFocus();
		Utils.showSoftInput(this.getActivity());
		//设置文本编辑框软键盘右下角按钮的点击事件监听器
		input_keyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				boolean isOK = true;
				switch (actionId) {
		            case EditorInfo.IME_ACTION_NONE:
		                Toast.makeText(getContext(), "点击-->NONE", Toast.LENGTH_SHORT).show();
		                break;
		            case EditorInfo.IME_ACTION_GO:
		                Toast.makeText(getContext(), "点击-->GO", Toast.LENGTH_SHORT).show();
		                break;
		            case EditorInfo.IME_ACTION_SEARCH:
		            	Utils.hideSoftInput(getActivity());
						String keyword = input_keyword.getText().toString();
						if(null != keyword && !"".equals(keyword)) {
							pullRefreshLayout.setRefreshing(true);
							SearchOnlineFragment.this.querySongSugOnline(keyword);
						}
		                //Toast.makeText(getContext(), "点击-->SEARCH", Toast.LENGTH_SHORT).show();
		                break;
		            case EditorInfo.IME_ACTION_SEND:
		                Toast.makeText(getContext(), "点击-->SEND", Toast.LENGTH_SHORT).show();
		                break;
		            case EditorInfo.IME_ACTION_NEXT:
		                Toast.makeText(getContext(), "点击-->NEXT", Toast.LENGTH_SHORT).show();
		                break;
		            default:isOK = false;break;
		        }
				return isOK;
			}
		});
		//下拉刷新和上啦加载更多
		pullRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				String keyword = input_keyword.getText().toString();
				if(null != keyword && !"".equals(keyword)) {
					pullRefreshLayout.setRefreshing(true);
					SearchOnlineFragment.this.querySongSugOnline(keyword);
				}
			}
		});
		pullRefreshLayout.setOnLoadMoreListener(new SwipeLayout.OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				if(isArtist) {
					//通过歌手id去分页查询歌手的歌曲列表
					BaiduMusicUtil.queryArtistSongList(art.getArtistid(), ++pageNo, pageSize, searchArtistSongListHandler);
				}else {
					pullRefreshLayout.finishLoading(false);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.icon_back_tomain://返回
				Utils.hideSoftInput(getActivity());
				Utils.go(this.getActivity().getSupportFragmentManager(), this, MainActivity.previous, R.id.framecontent);
				break;
			case R.id.btn_beginSearch://开始搜索
				Utils.hideSoftInput(getActivity());
				String keyword = input_keyword.getText().toString();
				if(null != keyword && !"".equals(keyword)) {
					pullRefreshLayout.setRefreshing(true);
					this.querySongSugOnline(keyword);
				}
				break;
			default:
				Utils.hideSoftInput(getActivity());
				break;
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		MainActivity main = (MainActivity)this.getActivity();
		if(!hidden) {
//			if(MainActivity.previous != MainActivity.lyricFragment) {
//				input_keyword.requestFocus();
//				Utils.showSoftInput(this.getActivity());
//			}
			main.setTopAndBottomActionBarVisibility(View.GONE, View.VISIBLE);
			MainActivity.previous = MainActivity.localMusicFragment;
		}else {
			main.setTopAndBottomActionBarVisibility(View.VISIBLE, View.VISIBLE);
		}
		super.onHiddenChanged(hidden);
	}
	
	/**
	 * 在线搜索SongSug
	 * @param keyword
	 * @param handler
	 */
	private void querySongSugOnline(String keyword) {
		pageNo = 1;
		searchSongAdapter.getSearchSongs().clear();
		BaiduMusicUtil.querySug(keyword, new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 200) {
					JSONObject obj = JSONObject.parseObject(msg.obj.toString());
					if(obj.getIntValue("error_code") == 22000) {
						if(obj.containsKey("artist")) {
							isArtist = true;
							//如果包含歌手信息  就通过歌手id去查询他的歌曲
							JSONArray artists = obj.getJSONArray("artist");
							art = JSON.parseObject(artists.get(0).toString(), Artist.class);
							//通过歌手id去分页查询歌手的歌曲列表
							BaiduMusicUtil.queryArtistSongList(art.getArtistid(), pageNo, pageSize, searchArtistSongListHandler);
						}else if(obj.containsKey("song")) {
							isArtist = false;
							JSONArray songs = obj.getJSONArray("song");
							tv_listview_itemcount.setText("共搜索到" + songs.size() + "条相关信息");
							SongSug ss = null;
							for(int i=0;i<songs.size();i++) {
								ss = JSON.parseObject(songs.get(i).toString(), SongSug.class);
								//通过歌曲id去查询歌曲详细信息
								BaiduMusicUtil.querySongInfo(ss.getSongid(), searchSongInfoHandler);
							}
						}
					}else{
						//一条数据都没搜索到
						tv_listview_itemcount.setText("未搜索到任何相关信息");
					}
				}else{
					Logs.writeLog("在线搜索异常", msg.obj.toString());
				}
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						pullRefreshLayout.finishRefreshing();
					}
				}, 1000);
			}
		});
	}
	
	
	
	
}
